<template>
    <div class="box">
        <div>
            <h1>商户登录</h1>
        </div>
        <div>
            <el-form
                ref="ruleFormRef"
                style="max-width: 600px"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
            >
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="ruleForm.mobile" />
                </el-form-item>

 
                <el-form-item label="图片验证码" required>
                    <el-col :span="11">
                        <el-form-item prop="imageCode">
                            <el-input v-model="ruleForm.imageCode" />
                        </el-form-item>
                    </el-col>
                    <el-col class="text-center" :span="2">
                        
                    </el-col>
                    <el-col :span="11">
                        <el-form-item>
                            <el-image :src="codeImageUrl" @click="onChangeImageCode"></el-image>
                        </el-form-item>
                    </el-col>
                </el-form-item>

                <el-form-item label="手机验证码" required>
                    <el-col :span="11">
                        <el-form-item prop="mobileCode">
                            <el-input v-model="ruleForm.mobileCode" />
                        </el-form-item>
                    </el-col>
                    <el-col class="text-center" :span="2">
                        
                    </el-col>
                    <el-col :span="11">
                        <el-form-item prop="date2">
                            <el-button @click="submitCodeForm(ruleFormRef)">发送验证码</el-button>
                        </el-form-item>
                    </el-col>
                </el-form-item>

                
                <el-form-item>
                    <el-button type="primary" @click="submitLoginForm(ruleFormRef)">
                        登录
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { sendCode,shopperLogin } from "@/api/api";
import { useRouter } from 'vue-router';

const router = useRouter();

interface RuleForm {
    mobile: string;
    imageCode: string;
    mobileCode: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
    mobile: "",
    imageCode: "",
    mobileCode: "",
});

const locationOptions = ["Home", "Company", "School"];

const rules = reactive<FormRules<RuleForm>>({
    mobile: [
        {
            required: true,
            message: "请输入手机号",
            trigger: "blur",
        },
        { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: "请输入正确的手机号", trigger: "blur" },
    ],
    imageCode: [
        {
            required: true,
            message: "请输入图形验证码",
            trigger: "blur",
        },
    ],
    mobileCode: [
        {
            required: true,
            message: "请输手机验证码",
            trigger: "blur",
        },
    ],
});

const codeImageUrl = ref('http://localhost:9001/user/index/imageCode')

// 刷新验证码
const onChangeImageCode = () => {
    codeImageUrl.value = 'http://localhost:9001/user/index/imageCode?t=' + new Date().getTime()
}

// 发送手机验证码
const submitCodeForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validateField(['mobile', 'imageCode'], (valid) => {
        if (valid) {
            // 校验通过，发送验证码
            sendCode(ruleForm).then(res => {
                if(res.data.code == 200) {
                    ElMessage.success('发送成功');
                }
                else {
                    ElMessage.error(res.data.msg);
                }
            })
        } else {
            // 表单校验不通过
            console.log("error submit!验证不通过");
        }
    });
};

const submitLoginForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 表单校验通过
            shopperLogin(ruleForm).then(res => {
                if(res.data.code == 200) {
                    ElMessage.success('登录成功');
                    // 保存token和用户信息
                    let user = res.data.data;
                    let token = user.token;
                    sessionStorage.setItem('token', token);
                    sessionStorage.setItem('user', JSON.stringify(user));

                    // 跳转页面
                    router.push('/home');
                }
                else {
                    ElMessage.error(res.data.msg);
                }
            })
        } else {
            // 表单校验不通过
            console.log("error submit!", fields);
        }
    });
};



const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}));
</script>
